const API_BASE = 'https://tihaidengta.xyz';

Page({
  data: {
    inputPassword: '',    // 设置密码时输入的
    generatedPassword: '', // 生成账号后保存的密码
    account: '',
    showPassword: false,
    serverUrl: 'http://47.119.146.254:8005/'
  },

  onLoad() {
    const storedUser = wx.getStorageSync('user') || {};
    const account = storedUser.account || wx.getStorageSync('generatedAccount') || '';
    const savedPassword = storedUser.password || '';

    if (account) {
      this.setData({
        account,
        generatedPassword: savedPassword
      });
    }
  },

  onPasswordInput(e) {
    this.setData({
      inputPassword: e.detail.value.trim()
    });
  },

  togglePasswordVisibility() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },

  generateAccount() {
    const { inputPassword } = this.data;
    if (!inputPassword) {
      wx.showToast({
        title: '请先输入密码',
        icon: 'none'
      });
      return;
    }
 // 新增：密码长度校验
 if (inputPassword.length < 8) {
  wx.showToast({
    title: '密码至少8位',
    icon: 'none'
  });
  return;
}

    wx.showLoading({ title: '请求中...' });

    const token = wx.getStorageSync('token') || '';

    wx.request({
      url: `${API_BASE}/eduservice/user/addAccount`,
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': token
      },
      data: { password: inputPassword },
      success: (res) => {
        wx.hideLoading();
        const storedUser = wx.getStorageSync('user') || {};
        const account = storedUser.account || wx.getStorageSync('generatedAccount') || '';

        if (account) {
          this.setData({ 
            account, 
            generatedPassword: inputPassword, 
            inputPassword: '' 
          });
          wx.setStorageSync('user', { ...storedUser, password: inputPassword });

          wx.showToast({
            title: '生成账号成功',
            icon: 'success'
          });
        } else {
          wx.showToast({
            title: '生成账号成功，但未找到本地账号，请稍后刷新',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    });
  },

  copyToClipboard(e) {
    const value = e.currentTarget.dataset.value;
    wx.setClipboardData({
      data: value,
      success: () => {
        wx.showToast({
          title: '已复制',
          icon: 'success'
        });
      }
    });
  }
});
